/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DlgProducers.java
 *
 * Created on Jul 12, 2011, 12:44:36 AM
 */
package OtherForms;

import Helpers.ImageFileView;
import Helpers.ImageFilter;
import Helpers.ImagePreview;
import Persistences.Products;
import Repositories.*;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import sun.awt.datatransfer.DataTransferer;

/**
 *
 * @author letuan
 */
public class DlgProducts extends javax.swing.JDialog {

    private JTextField txtIDCategory;
    private JTextField txtIDProducer;
    private JTextField txtIDDistributer;
    private JFileChooser fc;
    private File SelectedFile;
    public String DataTransfered;

    /** Creates new form DlgProducers */
    public DlgProducts(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** Creates new form DlgProducers */
    public DlgProducts(java.awt.Frame parent, boolean modal, boolean EnableChoose) {
        super(parent, modal);
        initComponents();
        btnChoose.setEnabled(EnableChoose);
        initHiddenFields();
        loadData();
    }

    public void initHiddenFields() {
        txtIDCategory = new JTextField();
        txtIDProducer = new JTextField();
        txtIDDistributer = new JTextField();
    }

    public void loadData() {
        ArrayList<Products> lstItem = new ArrayList<Products>();
        lstItem = ProductsRepository.selectAll();
        MyTable.TableProducts.loadDataIntoTableBook(tblData, lstItem);
    }

    public void loadInfoByID(int id) {
        Products item = ProductsRepository.selectByID(id);
        txtID.setText(String.valueOf(item.getId()));
        txtName.setText(item.getName());

        txtIDCategory.setText(item.getIdproductcategory() == null ? "" : String.valueOf(item.getIdproductcategory().getId()));
        txtCategory.setText(item.getIdproductcategory() == null ? "" : item.getIdproductcategory().getName());

        txtIDDistributer.setText(item.getIddistributor() == null ? "" : String.valueOf(item.getIddistributor().getId()));
        txtDistributer.setText(item.getIddistributor() == null ? "" : item.getIddistributor().getName());

        txtIDProducer.setText(item.getIdproducer() == null ? "" : String.valueOf(item.getIdproducer().getId()));
        txtProducer.setText(item.getIdproducer() == null ? "" : item.getIdproducer().getName());

        txtPrice.setText(String.valueOf(item.getPrice()));
        txtQuantity.setText(String.valueOf(item.getQuantity()));

        if (item.getPhoto() != null) {
            ImageIcon imageIcon = new ImageIcon(item.getPhoto());
            imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(
                    lblPhoto.getSize().width, lblPhoto.getSize().height, Image.SCALE_SMOOTH));

            lblPhoto.setIcon(imageIcon);
        }
    }

    public void resetInputData() {
        txtID.setText("");
        txtName.setText("");
        txtIDCategory.setText("");
        txtCategory.setText("");

        txtIDDistributer.setText("");
        txtDistributer.setText("");

        txtIDProducer.setText("");
        txtProducer.setText("");

        txtPrice.setText("");
        txtQuantity.setText("");

        SelectedFile = null;
        lblPhoto.setIcon(null);
    }

    public boolean validateInputData(AtomicReference<Object> errText) {
        if (txtName.getText().equals("")) {
            errText.set("Name is empty");
            return false;
        }
        if (txtIDCategory.getText().equals("")) {
            errText.set("Product Category is empty");
            return false;
        }
        if (txtPrice.getText().equals("")) {
            errText.set("Price is empty");
            return false;
        }
        if (txtQuantity.getText().equals("")) {
            errText.set("Quantity is empty");
            return false;
        }
        return true;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblData = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtID = new javax.swing.JTextField();
        txtName = new javax.swing.JTextField();
        txtCategory = new javax.swing.JTextField();
        btnChoose = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtProducer = new javax.swing.JTextField();
        txtPrice = new javax.swing.JTextField();
        txtQuantity = new javax.swing.JTextField();
        imgPhoto = new javax.swing.JPanel();
        lblPhoto = new javax.swing.JLabel();
        btnChooseCategory = new javax.swing.JButton();
        btnChooseProducer = new javax.swing.JButton();
        btnChoosePhoto = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        txtDistributer = new javax.swing.JTextField();
        btnChooseDistributor = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Products");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setLayout(new java.awt.BorderLayout());

        tblData.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3"
            }
        ));
        tblData.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblDataMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblData);

        jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel1.setBackground(java.awt.SystemColor.textHighlight);
        jPanel1.setPreferredSize(new java.awt.Dimension(50, 20));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jLabel5.setFont(new java.awt.Font("SansSerif", 1, 12));
        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("   List of Products");
        jPanel1.add(jLabel5, java.awt.BorderLayout.CENTER);

        jPanel3.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.add(jPanel3, java.awt.BorderLayout.LINE_START);

        jLabel1.setFont(new java.awt.Font("SansSerif", 1, 24));
        jLabel1.setForeground(new java.awt.Color(0, 153, 0));
        jLabel1.setText("Products Infomation");

        jLabel2.setText("ID");

        jLabel3.setText("Name");

        jLabel4.setText("Category");

        txtID.setEditable(false);

        txtCategory.setBackground(new java.awt.Color(255, 255, 255));
        txtCategory.setEditable(false);

        btnChoose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Sign-Select-icon.png"))); // NOI18N
        btnChoose.setText("Choose");
        btnChoose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseActionPerformed(evt);
            }
        });

        btnReset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Eraser-icon.png"))); // NOI18N
        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/001_29.png"))); // NOI18N
        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/81.png"))); // NOI18N
        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jLabel6.setText("Producer");

        jLabel8.setText("Price");

        jLabel9.setText("Quantity");

        jLabel10.setText("Image");

        txtProducer.setBackground(new java.awt.Color(255, 255, 255));
        txtProducer.setEditable(false);

        imgPhoto.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        imgPhoto.setPreferredSize(new java.awt.Dimension(135, 135));
        imgPhoto.setLayout(new java.awt.BorderLayout());
        imgPhoto.add(lblPhoto, java.awt.BorderLayout.CENTER);

        btnChooseCategory.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/001_03.gif"))); // NOI18N
        btnChooseCategory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseCategoryActionPerformed(evt);
            }
        });

        btnChooseProducer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/001_03.gif"))); // NOI18N
        btnChooseProducer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseProducerActionPerformed(evt);
            }
        });

        btnChoosePhoto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/001_03.gif"))); // NOI18N
        btnChoosePhoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChoosePhotoActionPerformed(evt);
            }
        });

        jLabel11.setText("Distributor");

        txtDistributer.setBackground(new java.awt.Color(255, 255, 255));
        txtDistributer.setEditable(false);

        btnChooseDistributor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/001_03.gif"))); // NOI18N
        btnChooseDistributor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseDistributorActionPerformed(evt);
            }
        });

        jLabel7.setText("USD");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel6)
                            .addComponent(jLabel11)
                            .addComponent(jLabel8)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10))
                        .addGap(24, 24, 24)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(txtCategory, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                        .addComponent(txtProducer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                        .addComponent(txtDistributer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                                        .addComponent(txtQuantity, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(txtPrice, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE))
                                    .addComponent(imgPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel7)
                                    .addComponent(btnChoosePhoto, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnChooseProducer, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnChooseCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnChooseDistributor, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(btnChoose)
                        .addGap(18, 18, 18)
                        .addComponent(btnReset)
                        .addGap(18, 18, 18)
                        .addComponent(btnDelete)
                        .addGap(18, 18, 18)
                        .addComponent(btnSave)))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnChooseCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 20, Short.MAX_VALUE)
                    .addComponent(txtCategory)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtProducer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6))
                    .addComponent(btnChooseProducer, javax.swing.GroupLayout.PREFERRED_SIZE, 20, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtDistributer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel11))
                    .addComponent(btnChooseDistributor, javax.swing.GroupLayout.PREFERRED_SIZE, 20, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnChoosePhoto)
                    .addComponent(imgPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnChoose)
                    .addComponent(btnReset)
                    .addComponent(btnDelete)
                    .addComponent(btnSave))
                .addGap(59, 59, 59))
        );

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-900)/2, (screenSize.height-541)/2, 900, 541);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowOpened

    private void tblDataMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDataMousePressed
        // TODO add your handling code here:
        int modifiers = evt.getModifiers();
        if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
            if (this.tblData.getSelectedRow() == -1) {
                return;
            }
            if (tblData.getValueAt(this.tblData.getSelectedRow(), 0) == null) {
                return;
            }
            if (evt.getClickCount() == 1) {
                String id = ((JLabel) tblData.getValueAt(this.tblData.getSelectedRow(), 0)).getName().trim();
                loadInfoByID(Integer.parseInt(id));
            }
        }
    }//GEN-LAST:event_tblDataMousePressed

    private void btnChooseCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseCategoryActionPerformed
        // TODO add your handling code here:
        DlgProductCategories dlg = new DlgProductCategories(null, true, true);
        dlg.show();
        if (!dlg.DataTransfered.equals("")) {
            String[] comp = dlg.DataTransfered.split("#");
            txtIDCategory.setText(comp[0]);
            txtCategory.setText(comp[1]);
        }
    }//GEN-LAST:event_btnChooseCategoryActionPerformed

    private void btnChooseProducerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseProducerActionPerformed
        // TODO add your handling code here:
        DlgProducers dlg = new DlgProducers(null, true, true);
        dlg.show();
        if (!dlg.DataTransfered.equals("")) {
            String[] comp = dlg.DataTransfered.split("#");
            txtIDProducer.setText(comp[0]);
            txtProducer.setText(comp[1]);
        }
    }//GEN-LAST:event_btnChooseProducerActionPerformed

    private void btnChooseDistributorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseDistributorActionPerformed
        // TODO add your handling code here:
        DlgDistributors dlg = new DlgDistributors(null, true, true);
        dlg.show();
        if (!dlg.DataTransfered.equals("")) {
            String[] comp = dlg.DataTransfered.split("#");
            txtIDDistributer.setText(comp[0]);
            txtDistributer.setText(comp[1]);
        }
    }//GEN-LAST:event_btnChooseDistributorActionPerformed

    private void btnChoosePhotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChoosePhotoActionPerformed
        // TODO add your handling code here
        if (fc == null) {
            fc = new JFileChooser();

            //Add a custom file filter and disable the default
            //(Accept All) file filter.
            fc.addChoosableFileFilter(new ImageFilter());
            fc.setAcceptAllFileFilterUsed(false);

            //Add custom icons for file types.
            fc.setFileView(new ImageFileView());

            //Add the preview pane.
            fc.setAccessory(new ImagePreview(fc));
        }

        //Show it.
        int returnVal = fc.showDialog(this, "Attach");

        //Process the results.
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            SelectedFile = fc.getSelectedFile();
            String pathImages = SelectedFile.getPath();

            ImageIcon imageIcon = new ImageIcon(pathImages);
            imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(
                    lblPhoto.getSize().width, lblPhoto.getSize().height, Image.SCALE_SMOOTH));

            lblPhoto.setIcon(imageIcon);
        }
        //Reset the file chooser for the next time it's shown.
        fc.setSelectedFile(null);
    }//GEN-LAST:event_btnChoosePhotoActionPerformed

    private void btnChooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseActionPerformed
        // TODO add your handling code here:
        DataTransfered = txtID.getText() + "#" + txtName.getText();
        this.dispose();
    }//GEN-LAST:event_btnChooseActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        // TODO add your handling code here:
        resetInputData();
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if (txtID.getText().equals("")) {
            return;
        }
        if (JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this item", "Announcement", JOptionPane.OK_CANCEL_OPTION) == 0) {
            String id = ((JLabel) tblData.getValueAt(this.tblData.getSelectedRow(), 0)).getName().trim();
            if (ProductsRepository.delete(Integer.parseInt(id))) {
                loadData();
                resetInputData();
                JOptionPane.showMessageDialog(null, "Item has been deleted",
                        "Announcement", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "Delete item fail",
                        "Announcement", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        boolean updated = false;
        AtomicReference<Object> errText = new AtomicReference<Object>("");

        if (!validateInputData(errText)) {
            JOptionPane.showMessageDialog(null, errText.get(),
                    "Announcement", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (txtID.getText().equals("")) {
            Products prod = new Products();
            prod.setName(txtName.getText());
            prod.setPrice(Long.parseLong(txtPrice.getText()));
            prod.setQuantity(Integer.parseInt(txtQuantity.getText()));

            if (!txtIDCategory.getText().equals("")) {
                prod.setIdproductcategory(ProductCategoriesRepository.selectByID(Integer.parseInt(txtIDCategory.getText())));
            }
            if (!txtIDDistributer.getText().equals("")) {
                prod.setIddistributor(DistributorsRepository.selectByID(Integer.parseInt(txtIDDistributer.getText())));
            }
            if (!txtIDProducer.getText().equals("")) {
                prod.setIdproducer(ProducersRepository.selectByID(Integer.parseInt(txtIDProducer.getText())));
            }
            if (SelectedFile != null) {
                byte[] bFile = new byte[(int) SelectedFile.length()];
                try {
                    FileInputStream fileInputStream = new FileInputStream(SelectedFile.getPath());
                    //convert file into array of bytes
                    fileInputStream.read(bFile);
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                prod.setPhoto(bFile);
            }
            if (ProductsRepository.insert(prod)) {
                updated = true;
            }
        } else {
            Products prod = ProductsRepository.selectByID(Integer.parseInt(txtID.getText()));
            prod.setName(txtName.getText());
            prod.setPrice(Long.parseLong(txtPrice.getText()));
            prod.setQuantity(Integer.parseInt(txtQuantity.getText()));

            if (!txtIDCategory.getText().equals("")) {
                prod.setIdproductcategory(ProductCategoriesRepository.selectByID(Integer.parseInt(txtIDCategory.getText())));
            }
            if (!txtIDDistributer.getText().equals("")) {
                prod.setIddistributor(DistributorsRepository.selectByID(Integer.parseInt(txtIDDistributer.getText())));
            }
            if (!txtIDProducer.getText().equals("")) {
                prod.setIdproducer(ProducersRepository.selectByID(Integer.parseInt(txtIDProducer.getText())));
            }
            if (SelectedFile != null) {
                byte[] bFile = new byte[(int) SelectedFile.length()];
                try {
                    FileInputStream fileInputStream = new FileInputStream(SelectedFile.getPath());
                    //convert file into array of bytes
                    fileInputStream.read(bFile);
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                prod.setPhoto(bFile);
            }
            if (ProductsRepository.save(prod)) {
                updated = true;
            }
        }
        if (updated) {
            loadData();
            JOptionPane.showMessageDialog(null, "Item has been updated",
                    "Announcement", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "Update item fail",
                    "Announcement", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DlgProducts dialog = new DlgProducts(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnChoose;
    private javax.swing.JButton btnChooseCategory;
    private javax.swing.JButton btnChooseDistributor;
    private javax.swing.JButton btnChoosePhoto;
    private javax.swing.JButton btnChooseProducer;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JPanel imgPhoto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblPhoto;
    private javax.swing.JTable tblData;
    private javax.swing.JTextField txtCategory;
    private javax.swing.JTextField txtDistributer;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtPrice;
    private javax.swing.JTextField txtProducer;
    private javax.swing.JTextField txtQuantity;
    // End of variables declaration//GEN-END:variables
}
